package com.tongyi.lizhishop.activitys;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.tongyi.lizhishop.R;
import com.tongyi.lizhishop.api.StoreApi;
import com.tongyi.lizhishop.beans.CommonResonseBean;
import com.tongyi.lizhishop.beans.StoreBean;
import com.tongyi.lizhishop.cache.RxCacheManager;
import com.tongyi.lizhishop.common.BaseActivity;
import com.tongyi.lizhishop.common.CommonObserver;
import com.tongyi.lizhishop.common.MatisseUtils;
import com.tongyi.lizhishop.managers.APIServiceManager;
import com.tongyi.lizhishop.utils.PromptDialogUtils;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;
import com.yanzhenjie.alertdialog.AlertDialog;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.zchu.rxcache.RxCache;
import com.zchu.rxcache.data.CacheResult;
import com.zchu.rxcache.stategy.CacheStrategy;
import com.zhihu.matisse.Matisse;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.leefeng.promptlibrary.PromptDialog;

import static com.tongyi.lizhishop.activitys.StoreManagerActivity.getRealPathFromURI;

public class TextDetailActivity extends BaseActivity implements MultiItemTypeAdapter.OnItemClickListener, RationaleListener, View.OnClickListener {

    private static final int REQUEST_CODE_CHOOSE = 2;
    @BindView(R.id.titlebar)
    CommonTitleBar titlebar;
    @BindView(R.id.activity_text_detail)
    LinearLayout activityTextDetail;
    @BindView(R.id.recycleview)
    RecyclerView recycleview;
    @BindView(R.id.changePassword)
    TextView changePassword;
    @BindView(R.id.content)
    EditText content;
    @BindView(R.id.editBtn)
    Button editBtn;

    ArrayList<Object> dataitems = new ArrayList<>();
    private CommonAdapter<Object> adapter;
    private PromptDialog prompDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_detail);
        ButterKnife.bind(this);
        dataitems.add("imageholder");
        prompDialog = PromptDialogUtils.getPrompDialog(this);

        initTitleBarView(titlebar, "图文详情");
        initView();
        loadData();
    }

    private void loadData() {
        prompDialog.showLoading("请等待");
        RxCache rxCache = RxCacheManager.getRxCache();
        APIServiceManager.getInstance().create(StoreApi.class)
                .infoSeller(SPUtils.getInstance().getString("userid"))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CommonObserver<StoreBean>() {
                    @Override
                    public void onSuccess(StoreBean value) {
                        prompDialog.dismissImmediately();
                        if ("succ".equals(value.getRe())) {
                            List<String> imagescontent = value.getArray().getImagescontent();
                            dataitems.addAll(dataitems.size() - 1, imagescontent);
                            adapter.notifyDataSetChanged();
                            String sel_content = value.getArray().getSel_content();
                            content.setText(sel_content);
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        prompDialog.dismissImmediately();
                        ToastUtils.showShort("请求数据失败!请检查网络");

                    }
                });
    }

    private void initView() {
        recycleview.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        adapter = new CommonAdapter<Object>(this, R.layout.activity_text_detail_recycleview_item, dataitems) {
            @Override
            protected void convert(ViewHolder holder, Object o, int position) {
                ImageView imageView = holder.getView(R.id.imageview);
                if (position == dataitems.size() - 1) {
                    imageView.setImageResource(R.mipmap.plus);
                } else {
                    Object model = dataitems.get(position);
                    if (model instanceof Uri) {
                        Glide.with(TextDetailActivity.this).load(model).into(imageView);
                    } else if (model instanceof String) {
                        Glide.with(TextDetailActivity.this).load(APIServiceManager.server_address + model).into(imageView);
                    }
                }

            }

            @Override
            public int getItemCount() {
                return super.getItemCount();
            }
        };
        adapter.setOnItemClickListener(this);
        recycleview.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        editBtn.setOnClickListener(this);
    }

    @Override
    public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {

        if (position == dataitems.size() - 1) {
            // 在Activity：
            AndPermission.with(this)
                    .requestCode(100)
                    .permission(Permission.STORAGE)
                    .rationale(this)
                    .callback(this)
                    .start();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            List<Uri> mSelected = Matisse.obtainResult(data);
            Log.d("Matisse", "mSelected: " + mSelected);
            for (final Uri uri : mSelected) {
                dataitems.add(dataitems.size() - 1, uri);
            }
            adapter.notifyDataSetChanged();
        }
    }


    @Override
    public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, final int position) {
        if (position == dataitems.size() - 1) {
            return false;
        }
        AlertDialog.newBuilder(this).setMessage("是否删除这张照片")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dataitems.remove(position);
                        adapter.notifyDataSetChanged();
                        dialog.dismiss();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show();
        return true;
    }

    private void selectPicFromLocal() {
        int maxSelectable = 6 - dataitems.size();
        if (maxSelectable > 0) {
            MatisseUtils.pickImage(this, maxSelectable, REQUEST_CODE_CHOOSE);
        } else {
            ToastUtils.showShort("您最多可选择5张照片");
        }
    }

    // 成功回调的方法，用注解即可，这里的300就是请求时的requestCode。
    @PermissionYes(100)
    private void getPermissionYes(List<String> grantedPermissions) {
        selectPicFromLocal();
    }

    @PermissionNo(100)
    private void getPermissionNo(List<String> deniedPermissions) {
        ToastUtils.showShort("请给予程序读取存储卡权限应用才能读取图片哦!");

    }

    @Override
    public void showRequestPermissionRationale(int requestCode, final Rationale rationale) {
        AlertDialog.newBuilder(this)
                .setTitle("提示")
                .setMessage("选择图片需要给程序读取内存的权限").setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                rationale.resume();
                dialog.dismiss();
            }
        });

    }


    /**
     * 上传图文详情
     */
    private void submitData2() {
        if (dataitems.size() == 1 || TextUtils.isEmpty(content.getText())) {
            ToastUtils.showShort("请选择照片和填写内容");
            return;
        }
        final PromptDialog prompDialog = PromptDialogUtils.getPrompDialog(this);
        prompDialog.showLoading("请等待");
        PostRequest<String> params = OkGo.<String>post(APIServiceManager.server_address + "/frontend.php/SelSeller/saveContent")
                .params("selid", SPUtils.getInstance().getString("userid"))
                .params("content", content.getText().toString());
        ArrayList<File> files = new ArrayList<>();
        for (int i = 0; i < dataitems.size(); i++) {
            Object uri1 = dataitems.get(i);
            if (uri1 instanceof Uri) {
                Uri uri = (Uri) uri1;
                String path = uri.getPath();
                LogUtils.w("path:" + path);
                String realPathFromURI = getRealPathFromURI(this, uri);
                files.add(new File(realPathFromURI));
            }
        }
        params.addFileParams("image", files);
        params.execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                Gson gson = new Gson();
                CommonResonseBean commonResonseBean = gson.fromJson(response.body().toString(), CommonResonseBean.class);
                LogUtils.w(response.body());
                if ("succ".equals(commonResonseBean.getRe())) {
                    prompDialog.showSuccess("提交成功", false);
                    Intent data = new Intent();
                    data.putExtra("status", 1);
                    setResult(RESULT_OK, data);
                    finish();
                } else {
                    prompDialog.showError("提交失败,请重试", false);
                }
            }
        });

    }

    @Override
    public void onClick(View v) {
        submitData2();
    }
}
